﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using My.Common.AutoMapper;
using My.Common.Configuration;

namespace Sale.DataAccess.Repository
{
    public class BaseRepository
    {
        private static SaleDataContext _context;

        protected SaleDataContext Context
        {
            get
            {
                if (_context == null)
                    _context = CreateNewContext();
                return _context;
            }
        }

        private SaleDataContext CreateNewContext()
        {
            var appConfig = new AppConfigurationManager();
            var connectionString = appConfig.GetConnectStringSetting("SaleDBConnectionString");
            return new SaleDataContext(connectionString);
        }

        protected AutoMapperBuilder ObjectMapper
        {
            get { return new AutoMapperBuilder(); }
        }

        public void SubmitChanges()
        {
            Context.SubmitChanges();
        }

        public void BeginTransaction()
        {
            if (Context.Connection.State != System.Data.ConnectionState.Open)
                Context.Connection.Open();
            Context.Transaction = Context.Connection.BeginTransaction();
        }

        public void CommitTransaction()
        {
            Context.Transaction.Commit();
            _context = CreateNewContext();
        }

        public void RollbackTransaction()
        {
            Context.Transaction.Rollback();
            _context = CreateNewContext();
        }

    }
}
